<?php

namespace front\modules\app\controllers;
use EasyWeChat\User\User;
use users\services\RegionService;
use wechat\services\PaymentService;
use Yii;
use yii\data\ActiveDataProvider;
use front\controllers\WebBaseController;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use order\services\OrderService;
use goods\services\ProductService;
use yii\helpers\ArrayHelper;
use goods\services\CartService;
use order\services\OrderUserService;
use coupons\services\CouponsGroupService;
use backend\services\ShopService;
use coupons\services\CouponsService;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order;
use EasyWeChat\Support\Url;
use yii\web\Cookie;


/**
 * OrderController implements the CRUD actions for OrderModel model.
 */
class OrderController extends WebBaseController
{
    //public $layout = 'main';

    private $_appId = '';

    private $_appSecret = '';

    private $_mch_id = '';

    private $_mch_key = '';

    private $getUserId;
    private $getUserIdInfo;

    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    public function init()
    {
        parent::init();

        $this->getUserId = isset($_POST['user_id']) ? Yii::$app->request->post('user_id'):0;
        $this->getUserIdInfo = isset($_GET['user_id']) ? Yii::$app->request->get('user_id'):0;
//        $wxpayRes = PaymentService::getPaymentConf();
//        $wxpayRes = $wxpayRes['result'];
//        $this->_appId = $wxpayRes['appId'];//'wxb92c2bb9c487c950';
//        $this->_appSecret = $wxpayRes['appSecret'];//'4531c2e3fcf9438320af5cb85b068549';
//        $this->_mch_id = $wxpayRes['mch_id'];//'1301495501';
//        $this->_mch_key = $wxpayRes['mch_key'];//'Yk3Bn8sBsg2yJ83gfkKHgfehe7Hdggsk';
    }
    /**
     * 订单购买页面
     *   $data= array(
            0=>  array('product_id'=> '1600034','num'=>'1','data'=> '颜色: 灰色','price'=>'123'),
            1=>  array('product_id'=> '1000007','num'=>'1','data'=> '颜色: 灰色','price'=>'123'),
          );
     */
    function actionBuy(){
        if($this->getUserId == 0){
            return $this->redirect('/web/user/login');
        }
        $orderPost = yii::$app->request->post();

        //post提交过来的参数
            $orderPost['hide_buy'] = isset($orderPost['hide_buy']) ? $orderPost['hide_buy']:'';
            //------------------------
            $total_price = $count = 0;
            $data=$groupInfo=[];
            $retailerId = isset($orderPost['retailerId'])&&$orderPost['retailerId'] ? $orderPost['retailerId']:'';
            if(isset($orderPost['product_id'])&&$orderPost['product_id']){
                $cartNum = CartService::oneProductCount($this->shop_id,$this->getUserId(),$orderPost['product_id']);

                //直接购买
                $data[0]['product_id'] = $orderPost['product_id'];
                $data[0]['shop_id'] =$this->shop_id;
                $data[0]['num'] = $orderPost['num'] + $cartNum;
                $productInfo = ProductService::ProductInfo($orderPost['product_id']);
                $productInfo['result'] = ArrayHelper::toArray($productInfo['result']);

                WebBaseController::getAjaxDataInfo(3,'库存不足');


                $data[0]['data']['item_attrText_map'] = isset($productInfo['result']['productInfo']['item_attrText_map']) ? $this->setAttrOrder($productInfo['result']['productInfo']['item_attrText_map']) : '';
                $data[0]['price'] = isset($productInfo['result']['productInfo']['price'])? $productInfo['result']['productInfo']['price']:'0.00';
                $data[0]['name'] =$productInfo['result']['productInfo']['name'];
                $data[0]['data']['thumb'] =$productInfo['result']['productInfo']['thumb'][0]. '@1e_1c_0o_0l_200h_200w_100q.jpg';
                $total_price += ($data[0]['price'] * $data[0]['num']);
                $count += $data[0]['num'];
            }

            if($retailerId){
                $res = $this->getOrder($retailerId);
                //购买之后不付款，支付返回
                //购物车产品信息
                foreach($res as $v){
                    $cartInfo[] = CartService::oneInfo($v['shop_id'],$this->getUserId,$v['product_id']);
                }
                if(!$cartInfo[0]){
                    return $this->redirect('/web/order/index');
                }

                $coupons = [];
                foreach($cartInfo as $k=>$v){
                    $data[$k]['product_id'] = $v['product_id'];
                    $data[$k]['shop_id'] = $v['shop_id'];
                    $data[$k]['num'] = $v['num'];
                    $goodsinfo[$k]= ProductService::ProductInfo($v['product_id']);
                    $goodsinfo[$k]['result'] = ArrayHelper::toArray($goodsinfo[$k]['result']);

                    if($goodsinfo[$k]['result']['productInfo']['stock']<=0 || $goodsinfo[$k]['result']['productInfo']['stock']<$v['num']){
                        WebBaseController::getAjaxDataInfo(3,$goodsinfo[$k]['result']['productInfo']['name'].'库存不足');
                    }


                    $data[$k]['price'] = isset($goodsinfo[$k]['result']['productInfo']['price']) ? $goodsinfo[$k]['result']['productInfo']['price'] :'0.00';
                    $data[$k]['data']['thumb'] = isset($goodsinfo[$k]['result']['productInfo']['thumb'][0])?$goodsinfo[$k]['result']['productInfo']['thumb'][0]. '@1e_1c_0o_0l_200h_200w_100q.jpg':"";
                    $data[$k]['name'] = isset($goodsinfo[$k]['result']['productInfo']['name']) ? $goodsinfo[$k]['result']['productInfo']['name'] :'';
                    $data[$k]['data']['item_attrText_map'] = isset($goodsinfo[$k]['result']['productInfo']['item_attrText_map']) ?
                        $this->setAttrOrder($goodsinfo[$k]['result']['productInfo']['item_attrText_map']) : '';
                    $total_price += ($data[$k]['price'] * $data[$k]['num']);
                    $count += $data[$k]['num'];
                    //获取卡券商品信息
                    $productInfo = ProductService::ProductInfo($cartInfo[$k]['product_id']);
                    $promotions = isset($productInfo['result']['productInfo']['promotion']) ? $productInfo['result']['productInfo']['promotion']:array();
                    //循环取出卡券信息,如果不存在之前的商品已经包含该卡券组ID,把组ID加入数组中
                    foreach ($promotions as $item) {
                        if (!in_array($item,$coupons)) {
                            array_push($coupons,$item);
                        }
                    }
                }

                //根据卡券组id,获取卡券活动的具体信息
                foreach ($coupons as $item) {
                    $info = CouponsGroupService::getGroupInfo($item);
                    $coupons_data['type'] = isset($info['result'][0]['type']) ? $info['result'][0]['type'] : '';
                    $coupons_data['groupInfo'] = $info['result'][0];
                    //判断是否用户已经领取卡券,并获取领取的卡券具体信息
                    $userGroupInfo = CouponsService::userCouponsInfo($item,$this->getUserId);
                    if (isset($userGroupInfo['code']) && $userGroupInfo['code'] == 0) {
                        $coupons_data['coupons_id'] = $userGroupInfo['result'][0]['coupons_id'];
                        $coupons_data['coupons_status'] = $userGroupInfo['result'][0]['status'];
                        array_push($groupInfo,$coupons_data);
                    }
                }
                //对象转换为数组
                $groupInfo = ArrayHelper::toArray($groupInfo);

            }


        $list['total_price'] = isset($total_price) ? $total_price : 0 ;
        $list['count'] = isset($count) ? $count : 0 ;
        $list['product'] = isset($data) ? $data : [] ;
        //用户线上购买地址
        $res['user_id'] = $this->getUserId;
        $res['getByWeb']=1;
        //选择收货地址
        $res['default'] = 1; //1是默认地址 0不是

        //用户默认地址
        $userSite = OrderUserService::search($res);
        $address = ArrayHelper::toArray($userSite['result']);
        if($address){
            $addrRes = isset($address[0]['district']) ? self::getDistrict_char($address[0]['district']):'';
            $address[0]['district_char'] = isset($addrRes['district_char'])?$addrRes['district_char']:"";
            $address[0]['merger'] = isset($addrRes['merger']) ? $addrRes['merger']:'';
            $address[0]['address'] = isset($addrRes['merger'])&&isset($address[0]['address'])?$addrRes['merger']. $address[0]['address']:"";
        }
        $list['user_site'] =  $address;
        $list['uid'] = $this->getUserId;
        $list['hide_buy'] = isset($orderPost['hide_buy']) ? $orderPost['hide_buy'] : '';

        WebBaseController::getAjaxDataInfo(0,'success',$list);
    }


    /**
     * Array ( [name] => 吴祥 [default] => 1 [district] => 0310101 [address] => 世纪大道2123号 [mobile] => 15000104006 )
     */
    function actionAddaddrinfo(){
        $getPost = yii::$app->request->post();
        $getPost['user_id'] = $this->getUserId;
        if(!preg_match('/^0?1[3|4|5|7|8][0-9]\d{8}$/',$getPost['mobile'])){
            WebBaseController::getAjaxDataInfo(2,'手机号码添加错误');
        }
        OrderUserService::addAddress($getPost);
        WebBaseController::getAjaxDataInfo(0,'success');
    }

    function actionEditaddrinfo(){
        $arr=[];
        $getPost = yii::$app->request->post();
        if(!preg_match('/^0?1[3|4|5|7|8][0-9]\d{8}$/',$getPost['mobile'])){
            WebBaseController::getAjaxDataInfo(2,'手机号码添加错误');
        }
        $data['id'] =$getPost['id'];
        $data['getByWeb']=1;
        $info = OrderUserService::search($data);
        $address = ArrayHelper::toArray($info['result']);
        $defaultAddr = $address[0]['default'];
        if($defaultAddr==1){
            $getPost['default']=1;
        }
        $getPost['dist_cn_char'] = '0';
        $getPost['tel']='0';
        $info = OrderUserService::update($getPost);
        if($info['code']==0){
            WebBaseController::getAjaxDataInfo(0,'success');
        }

    }

    function actionAddaddrself(){
        $type = Yii::$app->request->get('type');
        $address = ShopService::getAllAddress();
        $address = ArrayHelper::toArray($address);
        WebBaseController::getAjaxDataInfo(0,'success',$address);
    }

    //是否取消的地址是否是默认收货地址，
    function actionIsremoveaddr(){
        $data['id'] = yii::$app->request->post('addid');
        $data['getByWeb']=1;
        $info = OrderUserService::search($data);
        if(isset($info)){
            $address = ArrayHelper::toArray($info['result']);
            return json_encode($address[0]);
        }

    }

    /**
     * get char
     * @return mixed
     * 获取地址具体信息
     */
    private static function getDistrict_char($district) {
        $pro = substr($district, 0 , 2);
        $city = substr($district, 0 , 4);
        $merger_name = RegionService::getMesgerName($district);
        $nameArr = explode(',', $merger_name);
        $ret['district_char'] = $pro . '|' . $city . '|' . $district . ',' . $nameArr[1] . '|' . $nameArr[2] . '|' . $nameArr[3];
        $ret['merger'] =  $nameArr[1] . '|' . $nameArr[2] . '|' . $nameArr[3];
        return $ret;
    }

    /**
     * 回调url
     */
    function getUrl(){
        $redirect_uri =  'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        return $redirect_uri;
    }

    //创建签名SHA1
    function genSha1Sign($Parameters){
        $signPars = '';
        ksort($Parameters);
        foreach($Parameters as $k => $v) {
            if("" != $v && "sign" != $k) {
                if($signPars == '')
                    $signPars .= $k . "=" . $v;
                else
                    $signPars .=  "&". $k . "=" . $v;
            }
        }
        //$signPars = http_build_query($Parameters);
        $sign = SHA1($signPars);
        $Parameters['sign'] = $sign;
        return $sign;
    }


    function getPromotion($data){
        foreach($data as $key=>$val){
            $data[$key]= CouponsGroupService::getGroupInfo($val);
            $data[$key]= isset($data[$key]['result']) ? ArrayHelper::toArray($data[$key]['result']) : '';
            if(count($data[$key][0])<2){
                unset($data[$key]);
            }
            if(isset($data[$key][0]['group_id'])){
                $data[$key][0]['counpos'] =  CouponsService::userCouponsInfo($data[$key][0]['group_id'],$this->getUserId());
                if(isset($data[$key][0]['counpos'])){
                    foreach($data[$key][0]['counpos'] as $k=>$v){
                       if(!is_array($v)){
                           unset($data[$key]);
                       }
                    }
                }
            }
        }
       return $data;

    }





    /**
     * @param $data
     * @return array
     */
    function getOrder($data){
        foreach($data as $k=>$v){
           $arr[] = explode(',',$v);
        }
        foreach($arr as $key => $val){
            $res[$key]['product_id'] = $val[0];
            $res[$key]['shop_id'] = $val[1];
        }
        return $res;
    }


    //获取用户卡券
    function getCoupins($data){
        foreach($data as $k=>$v){
            $arr[] = CouponsGroupService::getGroupInfo($v['group_id']);
        }
        foreach($arr as $key=>$val){
            $arr[$key]['result'] = ArrayHelper::toArray($val['result']);
            $arr[$key]['result']['discount'] = isset($arr[$key]['result']['discount']) ? unserialize($arr[$key]['result']['discount']) : '';
            $arr[$key]['result']['product_id'] = isset($arr[$key]['result']['product_id']) ?unserialize($arr[$key]['result']['product_id']) : '';
        }
        return $arr;
    }


    /**
     * 结算
     * 前台参数格式：如两个商品 $cartProduct[0]=array('product_id'=> '131411','num'=>'1','data'=> '15151'),
     */
    public function submit($data)
    {
        $total_price = 0;
        foreach ($data as $k=>$v) {
            $data[$k]['price'] = ProductService::getPrice($v['product_id']);
            $data[$k]['price'] = ArrayHelper::toArray($data[$k]['price']);
            $data[$k]['price'] = $data[$k]['price']['price'];
            $total_price = $total_price + ($data[$k]['price'] * $data[$k]['num']);
        }
        return ['data' => $data, 'total_price' => $total_price];
    }

    /**
     * Lists all OrderModel models.
     * @return mixed
     * 订单列表
     * param用户id
     * 订单状态 0:待支付 1:待出库 2:已支付 3:待发货 4:已发货,等待收货
     * -1:供应商作废 -2:客户作废 -3:系统作废 -4:全部退货 -5:部分退货 -6:待审核 -7:退款
     * $arr = array(
        array(
            'oid'=>'10001', 'onum' => '10106546210', 'type'=> 1, 'list'=> array(
            '102' => array('title'=>'BOSS 佩戴时耳机', 'price'=> '888', 'attr'=>'颜色: 灰色', 'img'=>'img/tmp002.jpg'),
            '103' => array('title'=>'BOSS 佩戴时耳机', 'price'=> '888', 'attr'=>'颜色: 灰色', 'img'=>'img/tmp002.jpg')
            )
        ),
    );
     */
    public function actionIndex()
    {
        $data = Yii::$app->request->get();
        $data['customer_id'] = $this->getUserIdInfo;
        $type = yii::$app->request->get('type');
        $data['orderToC'] = 1;
        $data['getByWeb']=1;

        if($type==1){
            $data['status']=0;
        }
        if($type==2){
            $data['status']='4';
        }
        if($type==3){
            $data['status']='5';
        }


        $info = OrderService::findOrder($data);
        $info['result'] = ArrayHelper::toArray($info['result']);
        foreach($info['result'] as $k=>$v){
            $info['result'][$k]['orderItem'] = isset($v['order_id']) ?OrderService::findItems(['order_id'=>$v['order_id'],'getByWeb'=>1]) :array();
            $info['result'][$k]['orderItem'] = ArrayHelper::toArray($info['result'][$k]['orderItem']);
        }
        $arr=[];
        foreach($info['result'] as $key=>$val){
            $arr[$key]['oid'] = $val['order_id'];
            $arr[$key]['onum'] = $val['order_char_id'];
            $arr[$key]['type'] = $val['status'];
            $arr[$key]['product_id'] =$val['orderItem'][0]['product_id'];
            $arr[$key]['orderType'] = $this->getOrderType($val['status']);
            $arr[$key]['list']= $this->getProductAttr($val['orderItem']);
        }
        WebBaseController::getAjaxDataInfo(0,'success',$arr);
    }

    /**
     * 商品订单操作类型
     */
    function getOrderType($type){
        $arr = array(
            0=>'待付款',
            2=>'已支付',
            4=>'待收货',
            5=>'待评价',
            6=>'已评论'
        );

        $arrs = array(
            0=>'取消订单',
            4=>'查看物流',
            5=>'删除订单',
        );

        $arrss = array(
            0=>'付款',
            5=>'评价'
        );


        $res='';

       foreach($arr as $k=>$v){
           if($k==$type){
               $res[] = $v;
           }
       }
        foreach($arrs as $key=>$val){
            if($key==$type){
                $res[] = $val;
            }
        }

        foreach($arrss as $key3=>$val3){
            if($key3==$type){
                $res[] = $val3;
            }
        }
        return $res;
    }

    /**
     * @return string查看订单接口
     */
    public function actionAjaxorder()
    {
        $data = yii::$app->request->get();
        $data['customer_id'] = $this->getUserIdInfo;
        $status = yii::$app->request->get('type');
        $data['getByWeb']=1;
        if($status==1){
            $data['status']=0;
        }
        if($status==2){
            $data['status']='4';
        }
        if($status==3){
            $data['status']='5';
        }
        $data['orderToC'] = 1;
        $info = OrderService::findOrder($data);
        $info['result'] = ArrayHelper::toArray($info['result']);
        foreach($info['result'] as $k=>$v){
            $info['result'][$k]['orderItem'] = isset($v['order_id']) ?OrderService::findItems(['order_id'=>$v['order_id'],'getByWeb'=>1]) :array();
            $info['result'][$k]['orderItem'] = ArrayHelper::toArray($info['result'][$k]['orderItem']);
        }
        $arr = [];
        foreach($info['result'] as $key=>$val){
            $arr[$key]['oid'] = $val['order_id'];
            $arr[$key]['onum'] = isset($val['order_char_id'])?$val['order_char_id']:'';
            $arr[$key]['type'] =$val['status'];
            $arr[$key]['product_id'] =$val['orderItem'][0]['product_id'];
            $arr[$key]['list']= $this->getProductAttr($val['orderItem']);
        }
         WebBaseController::getAjaxDataInfo(0,'success',$arr);
    }


    //组装商品
    function getProductAttr($data){
        $arr=[];
        foreach($data as $k=>$v){
            $arr[$v['product_id']]['title'] = WebBaseController::msubstr($v['product_title'],0,30);
            $arr[$v['product_id']]['price'] = $v['price'];
            $arr[$v['product_id']]['attr'] = isset($v['data']) ? $this->setAttr($v['data'],$v['buy_num']) : '';
            $arr[$v['product_id']]['img'] = $v['product_pic_url'];
            $arr[$v['product_id']]['product_id'] = $v['product_id'];
        }
        return $arr;
    }

    /**
     * 获取价格 本来可以写成一个方法，但是这个方法是后写的
     */
    function getProoduct($pid){
        $res = ProductService::ProductInfo($pid);
        if($res['result']){
            $res['result'] = ArrayHelper::toArray($res['result']);
            $arr = isset($res['result']['productInfo']['price']) ? $res['result']['productInfo']['price'] : "";
        }
        return $arr;
    }

    /**
     * 组合属性
     */
    function setAttr($data,$buy_num){
        $res='';
        if($data){
            foreach($data as $k=>$v){
                $res.=$k.':'.$v.'<br/>';
            }
            $res.='数量:'.$buy_num;
        }else{
            $res.='数量:'.$buy_num;
        }
        return $res;
    }


    /**
     * 组合属性
     * <em>颜色：</em><i>蓝红</i>
    <em>尺码：</em><i>S</i>
    <em>数量：</em><i>1</i>
     */
    function setAttrOrder($data){
        $res='';
        unset($data['product_id']);
        foreach($data as $k=>$v){
            $res.='<em>'.$k.':</em><i>'.$v.'</i>';
        }
        return $res;
    }



    /**
     * 根据线上线下选择收货地址
     */
    function actionSetsite(){
        $res['siteid'] = intval(yii::$app->request->post('siteid'));
        $res['shopid'] = intval(yii::$app->request->post('shopid'));
        $res['uid'] = $this->getUserId();
        $res['default'] = 1; //1是默认地址 0不是
        $res['getByWeb']=1;
        //1用户线上购买地址,2线下支付
        if($res['siteid']==1){
            $userSite = OrderUserService::search($res);
            $userSite['result'] = ArrayHelper::toArray($userSite['result']);
            $list['user_site'] =  $userSite['result'];
        }else{
            $info = ShopService::getAddress($res['shopid']);
        }

    }



    /**
     * 插入订单
     * $data = [
    0 => [
    'seller_id' => 1000001059,
    'customer_id' => 1,
    'channel_source' => 1,
    'device_source' => 1,
    'order_users_id' => 4,
    'remark' => '备注信息000',
    'express' => [
        name => 八个字
        district => 1024
        address => 宜山路200号518室
        tel => 13112345678
        mobile => 56131214
     ]
    'item' => [
        0 => [
        'product_id' => '603614611',
        'price' => 22.33,
        'buy_num' => 2,
        'data' => [
        'color' => '红色',
        'size' => '大',
        ]
        ],
        1 => [
        'product_id' => '603614611',
        'price' => 22.33,
        'buy_num' => 10,
        'data' => [
        'color' => '红色',
        'size' => '大',
        ]
        ],
    ]
    ]
    ];

     */
    function actionCreate(){
        //订单表
        $data=Yii::$app->request->post();
        if(empty($data['goods'])){
            WebBaseController::getAjaxDataInfo(5,'结算商品不存在');
        }
        if(empty($data['express'])){
            WebBaseController::getAjaxDataInfo(4,'请选择快递');
        }
        if(empty($data['pay'])){
            WebBaseController::getAjaxDataInfo(5,'请选择支付方式');
        }
        if(empty($data['express_time'])){
            WebBaseController::getAjaxDataInfo(6,'请选择送货时间');
        }
        if(empty($data['address'])){
            WebBaseController::getAjaxDataInfo(12,'请填写收货地址');
        }

        $goodsInfo = explode('**',$data['goods']);
        foreach($goodsInfo as $k=>$v){
             $goodsAll[] = explode('#',$v);
        }

        foreach($goodsAll as $k=>$v){
            //购物车里是否有商品
            $cartInfo = CartService::oneInfo($this->shop_id,$this->getUserId,$v[0]);
            $goods[$k]['product_id'] = $v[0];
            $pro= ProductService::ProductInfo($v[0]);
            $pro['result']['productInfo'] = ArrayHelper::toArray($pro['result']['productInfo']);
            //判断库存是否存在或者小于购买数量
            if(isset($pro['result']['productInfo'])&&$pro['result']['productInfo']){
                if($pro['result']['productInfo']['stock']<=0 || $pro['result']['productInfo']['stock']<$v[1]){
                    WebBaseController::getAjaxDataInfo(8,$pro['result']['productInfo']['name'].'库存不足');
                }
            }

            $goods[$k]['thumb'] = isset($pro['result']['productInfo']['thumb'][0]) ? $pro['result']['productInfo']['thumb'][0]. '@1e_1c_0o_0l_200h_200w_100q.jpg':'';
            $goods[$k]['item_attrText_map'] = isset($pro['result']['productInfo']['item_attrText_map']) ? $pro['result']['productInfo']['item_attrText_map']: '';
            $goods[$k]['data'] = $goods[$k]['item_attrText_map'];
            unset($goods[$k]['item_attrText_map']);

            $goods[$k]['buy_num'] = $v[1]+$cartInfo['num'];
            $goods[$k]['price'] = ProductService::ProductInfo($v[0]);
            $goods[$k]['price'] = ArrayHelper::toArray($goods[$k]['price']['result']);
            $goods[$k]['price'] = isset($goods[$k]['price']['productInfo']['price']) ? $goods[$k]['price']['productInfo']['price']:'';
            $goods[$k]['price'] = $goods[$k]['price'];
            $goods[$k]['name'] = ProductService::ProductInfo($v[0]);
            $goods[$k]['name'] = ArrayHelper::toArray($goods[$k]['name']['result']);
            $goods[$k]['name'] = isset($goods[$k]['name']['productInfo']['name'])?$goods[$k]['name']['productInfo']['name']:'';
            $goods[$k]['name'] = $goods[$k]['name'];
        }

        $arr['seller_id'] = 100101;
        $arr['customer_id'] = $this->getUserId;
        $arr['remark'] = $data['remark'];  //留言
        $arr['order_users_id'] = $data['address']?$data['address']:0; //送货地址
        $res['getByWeb']=1;
        $res['id'] = $arr['order_users_id'];
        $address_info = OrderUserService::search($res);
        $userSite['result'] = ArrayHelper::toArray($address_info['result']);
        if($data['express']==3){
            $data['express']='快递';
        }else{
            $data['express']='自提';
        }

        if($data['express_time']==5){
            $data['express_time']='只工作日送货';
        }else{
            $data['express_time']='只双休日、节假日送货';
        }

        $userSite['result'][0]['pickup']=$data['express']; //选择快递
        $userSite['result'][0]['pickup_time']=$data['express_time']; //送货时间

        $self_address = ShopService::getAddress($data['express_self']);
        $userSite['result'][0]['express_self'] =  $self_address;  //自提地址

        $arr['express'] = $userSite['result'][0];   //快递信息和收货人地址
        $arr['payment_type'] = $data['pay'];  //支付方式
        $arr['channel_source'] = 1; //订单渠道来源
        $arr['device_source'] = 1; //订单来源设备
        $arr['item'] = $goods;

        $arr['discount'] = 0;
        $arrs[] = $arr;

        $services = new OrderService();
        $p = $services->placeOrder($arrs);

        if($p['code']==1){
            WebBaseController::getAjaxDataInfo(2,'购买失败');
        }
        //删除购物车里的该商品
        foreach($goodsAll as $item){
            if($item){
                CartService::deleteProduct($this->shop_id,$this->getUserId,$item[0]);
            }
        }
        $goodsorder['order_id'] =  $p['result']['order_id'];
        $goodsorder['getByWeb']=1;
        $goodsList = OrderService::findItems($goodsorder);
        foreach($goodsList as $key=>$val){
            $stock[$val['product_id']] = $this->getBuyStock($val['product_id'],$val['buy_num'],1);
        }
        foreach($stock as $stkey=>$stval){
            ProductService::updateStock($stkey,$stval);
        }
       // if($data['pay']==2){  //线下支付
        $info['order_id']  = $p['result']['order_id'];
        $info['pay_type']  = $data['pay'];
        WebBaseController::getAjaxDataInfo(0,'success',$info);

    }

    function getProductStr($pid){
        $res=$rest=$rr=[];
        $goodsDetail = ProductService::ProductInfo($pid);
        $arr= ArrayHelper::toArray($goodsDetail['result']['productInfo']);
        if(isset($arr['item_url_map'])){
            foreach($arr['item_url_map'] as $k=>$v){
                if($pid==$v['product_id']){
                    $res = isset($arr['item_url_map'][$k])?$arr['item_url_map'][$k]:array();
                    unset($res['product_id']);
                }
            }
            return $res;
        }
    }

    /**
     * 取消订单
     * status=-2
     */
    function actionCancelorder(){
        $data = yii::$app->request->get();
        if(!$data['cancel_order']){
            WebBaseController::getAjaxDataInfo(2,'订单不存在');
        }
       $res[0]['order_id'] = intval($data['cancel_order']);
       $res[0]['status']='-2';
       $info =  OrderService::changeStatus($res);
       if($info['code']==1){
           WebBaseController::getAjaxDataInfo(3,'错误操作');
       }
        if($info['code']==0){
            $rest['order_id'] = intval($data['cancel_order']);
            $rest['getByWeb']=1;
            $orders = OrderService::findItems($rest);
            $orders= ArrayHelper::toArray($orders);
            foreach($orders as $key=>$val){
                $stock[$val['product_id']] = $this->getBuyStock($val['product_id'],$val['buy_num'],2);
            }
            foreach($stock as $stkey=>$stval){
                ProductService::updateStock($stkey,$stval);
            }
            WebBaseController::getAjaxDataInfo(0,'success');
        }


    }

    function getBuyStock($pid,$num,$type=''){
        $goodsDetail = ProductService::ProductInfo($pid);
        $arr= ArrayHelper::toArray($goodsDetail['result']['productInfo']);

        if($type==1){
            $stock = $arr['stock']-$num;
        }elseif($type==2){
            $stock = $arr['stock']+$num;
        }
        return $stock;
    }
    /**
     *删除订单
     * is_hidel=1
     */
    function actionDelorder(){
        $data = yii::$app->request->get();
        if(!$data['del_order']){
            WebBaseController::getAjaxDataInfo(2,'订单不存在');
        }
        $res['order_id'] = intval($data['del_order']);
        $info =  OrderService::toHide($res);
        if($info['code']==1){
            WebBaseController::getAjaxDataInfo(3,'错误操作');
        }
        WebBaseController::getAjaxDataInfo(0,'success');

    }

    /**
     * 自提地址提交成功
     */
    function actionConfirminfo(){
        $data = yii::$app->request->get();
        if(!isset($data['order_id'])){
           WebBaseController::getAjaxDataInfo(2,'订单不存在');
        }

        if (Yii::$app->request->post()) {
            $getPost = yii::$app->request->post();
            $data['order_id'] = $getPost['order_id'];
            $data['express']['name'] = $getPost['name'];
            $data['express']['mobile'] = $getPost['mobile'];
            $result = OrderService::updateExpressInfo($data);
            if($result['code']==0){
                WebBaseController::getAjaxDataInfo(0,'success');
            }

        }else{
            $data['getByWeb']=1;
            $arr = OrderService::findOrder($data);
            $arr['result'] = ArrayHelper::toArray($arr['result']);
            $orders=[];
            foreach($arr['result'] as $k=>$v){
                $orders['order_id'] = $v['order_id']; //总价
                $orders['order_cost'] = $v['order_cost']; //总价
                $orders['order_char_id'] = $v['order_char_id']; //总价
                $orders['remark'] = $v['remark'];
                $orders['express'] = $v['express'];
                $orders['item'] = OrderService::findItems($data);
                foreach($orders['item'] as $key=>$val){
                    $orders['item'][$key] = ArrayHelper::toArray($val);
                }
            }

            WebBaseController::getAjaxDataInfo(0,'success',$orders);
        }
    }

    //自提订单成功之后显示的页面
    public function actionOrdersuccess() {
        return $this->render('ordersuccess');
    }

    /**
     * 订单成功
     */
    public function actionPayment(){
        $data = yii::$app->request->get();
        if(!isset($data['order_id'])){
            return false;
        }
       $data['getByWeb']=1;
       $arr = OrderService::findOrder($data);
       $arr['result'] = ArrayHelper::toArray($arr['result']);
       $orders=[];
       foreach($arr['result'] as $k=>$v){
           $orders['order_id'] = $v['order_id']; //总价
           $orders['order_cost'] = $v['order_cost']; //总价
           $orders['remark'] = $v['remark'];
           $orders['express'] = $v['express'];
           $orders['item'] = OrderService::findItems($data);
               foreach($orders['item'] as $key=>$val){
                   $orders['item'][$key] = ArrayHelper::toArray($val);
               }
       }

        $body = "";
        $product_title = "";
        $orderItem = $orders['item'];

        if (sizeof($orderItem) == 1) {
            $body = self::title_substr($orderItem[0]['product_title'],15);
            $product_title = $orderItem[0]['product_title'];
        }else if (sizeof($orderItem) > 1) {
            $body = self::title_substr($orderItem[0]['product_title'],13) . " 及其他" . sizeof($orderItem) . "件商品";
            $product_title = $orderItem[0]['product_title'];
            for ($i = 1 ; $i <= sizeof($orderItem) - 1; $i++) {
                $product_title .= "<br/> + " . $orderItem[$i]['product_title'];
            }
        }

        return $this->render('payment',[
            'totalprice' => $orders['order_cost'],
            'body' => $product_title,
            'payment' =>  $this->pay($body, $orders['order_id'], $orders['order_cost']*100)
        ]);
    }

    //支付成功之后显示的页面
    public function actionSuccess() {
        return $this->render('success');
    }

    //创建签名SHA1
    private function getSha1Sign($Parameters){
        $signPars = '';
        ksort($Parameters);
        foreach($Parameters as $k => $v) {
            if("" != $v && "sign" != $k) {
                if($signPars == '')
                    $signPars .= $k . "=" . $v;
                else
                    $signPars .=  "&". $k . "=" . $v;
            }
        }
        //$signPars = http_build_query($Parameters);
        $sign = SHA1($signPars);
        $Parameters['sign'] = $sign;
        return $sign;
    }

    //控制标题长度
    private function title_substr($title,$long) {
        $pa = '/./us';
        preg_match_all($pa, $title, $r);
        $count = count($r[0]);
        if ($count > $long) {
            $title = mb_substr($title,0,$long,'utf-8')."...";
        }
        return $title;
    }

    //支付相关
    private function pay($body, $orderId, $totalPrice)
    {
        $callback_url = 'http://shopbox.10000dt.com/web/pay/notify_3';

        $options = [
            'app_id' => $this->_appId,
            'payment' => [
                'merchant_id'        => $this->_mch_id,
                'key'                => $this->_mch_key,
//                'cert_path'          => 'path/to/your/cert.pem', // XXX: 绝对路径！！！！
//                'key_path'           => 'path/to/your/key',      // XXX: 绝对路径！！！！
                'notify_url'         => $callback_url,       // 你也可以在下单时单独设置来想覆盖它
            ],
        ];

        $app = new Application($options);
        $payment = $app->payment;

        $attributes = [
            'body' => $body,
            'detail' => $body,
            'out_trade_no' => $orderId,
            'total_fee' => $totalPrice,
            'notify_url' => $callback_url, // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI',
            'openid' => $this->openId//
        ];
        $order = new Order($attributes);

        $result = $payment->prepare($order);//

        $prepayId = $result->prepay_id;

        $json = $payment->configForPayment($prepayId);

        return $json;
    }
}
